package teatime.core.web.interceptor;

import java.io.PrintWriter;
import java.io.StringWriter;

import teatime.core.exception.BusinessException;
import teatime.core.utils.BusinessLogger;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;


/**
 * a simple exception handler interceptor, catch any uncaught exceptions, log
 * and return to global "exception" result.
 * 
 * @author Quake Wang
 * @since 2005-1-20
 * @version $Revision: 1.1 $
 */
public class ExceptionInterceptor implements Interceptor {

	private static final long serialVersionUID = 4109823881808608100L;

	public static final String EXCEPTION = "exception";

	public static final String ERROR = "error";

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init() {
		// TODO Auto-generated method stub

	}

	public String intercept(ActionInvocation invocation) throws Exception {
		BusinessLogger.getLogger().info(
				"[Action Begin]"
						+ invocation.getAction().getClass().getName()
						+ "@" + invocation.getInvocationContext().getName());
		try {
			String result = null;
			result = invocation.invoke();
			BusinessLogger.getLogger().info(
					"[Action End In Success]");
			return result;
		} catch (BusinessException be) {
			invocation.getInvocationContext().put("_error_trigger_",
					be.getTrigger());
			invocation.getInvocationContext().put("_error_message_",
					be.getMessage());
			// 操作日志
			BusinessLogger.getLogger().info(
					"[Action End In Exception]");
			return ERROR;
		} catch (Exception e) {
			String message = "Caught exception while invoking action: "
					+ invocation.getAction();
			BusinessLogger.getLogger().error(message, e);

			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			invocation.getInvocationContext().put("_exception_string_",
					sw.toString());
			// 操作日志
			BusinessLogger.getLogger().info(
					"[Action End In Exception]");
			return ERROR;
		}
	}

}